package com.kh.samr.commens;

import com.kh.samr.utils.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Objects;

/**
 * 全局异常处理类
 *
 * @author Harry
 * @date 2020/12/2
 */
@RestControllerAdvice
public class GlobalExceptionAdvisor {
	
	private static final Logger log = LoggerFactory.getLogger(GlobalExceptionAdvisor.class);
	
	private static String getMsg(Exception e) {
		StackTraceElement[] stackTrace = e.getStackTrace();
		StringBuilder sb = new StringBuilder();
		sb.append(e.toString()).append("\r\n");
		for (StackTraceElement stackTraceElement : stackTrace) {
			sb.append("\tat")
					.append(stackTraceElement.getClassName())
					.append(".")
					.append(stackTraceElement.getMethodName())
					.append("(")
					.append(stackTraceElement.getFileName())
					.append(":")
					.append(stackTraceElement.getLineNumber())
					.append(")\r\n");
		}
		return sb.toString();
	}
	
	/**
	 * 参数校验异常处理
	 *
	 * @param exception 参数校验异常
	 * @return 处理结果
	 */
	@ExceptionHandler(MethodArgumentNotValidException.class)
	public ResultUtil<String> validationBodyException(MethodArgumentNotValidException exception) {
		BindingResult result = exception.getBindingResult();
		log.error("全局异常：validationBodyException;返回值：" + Objects.requireNonNull(result.getFieldError()).getDefaultMessage());
		return new ResultUtil<>(exception.hashCode(),
				Objects.requireNonNull(result.getFieldError()).getDefaultMessage());
	}
}
